/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Unsafe from './Unsafe';
import Arrays from '../util/Arrays';
import Long from '../util/long/index'

export default class Histogram {
    constructor() {
    }

    private static countLarge(inputBase: any, inputAddress: Long, inputSize: number, counts: Int32Array): void
    {
        let input: Long = inputAddress;

        Arrays.fill(counts, 0);

        for (let i: number = 0; i < inputSize; i++) {
            let symbols: number = Unsafe.getByte(inputBase, input.toNumber()) & 0xFF;
            input = input.add(1);
            counts[symbols]++;
        }
    }

    public static findLargestCount(counts: Int32Array, maxSymbol: number): number
    {
        let max: number = 0;
        for (let i: number = 0; i <= maxSymbol; i++) {
            if (counts[i] > max) {
                max = counts[i];
            }
        }

        return max;
    }

    public static findMaxSymbol(counts: Int32Array, maxSymbol: number): number
    {
        while (counts[maxSymbol] == 0) {
            maxSymbol--;
        }
        return maxSymbol;
    }

    public static count(input: Int8Array, length: number, counts: Int32Array): void{
        Histogram.countLarge(input, Long.fromNumber(Unsafe.ARRAY_BYTE_BASE_OFFSET), length, counts);
    }
}
